package com.starblink.message.messagesystem.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.rocketreserver.FetchUserMessagesV2Query
import kotlinx.coroutines.launch

class MessageSystemVM : BaseViewModel() {
    var curPageNo = 0
    // 保存全部消息数据
    private val listResponse: ListResponse = ListResponse()
    // 普通列表数据
    val listResponseLiveData: MutableLiveData<ListResponse> =
        MutableLiveData()

    /**
     * 保存服务器返回数据
     */
    inner class ListResponse {
        val totalList = ArrayList<FetchUserMessagesV2Query.FetchUserMessagesV2>() // 保存全部列表数据
        lateinit var pageList: List<FetchUserMessagesV2Query.FetchUserMessagesV2> // 保存单页请求数据
        var refresh: Boolean = true // true-下拉刷新，false表示加载更多
    }

    /**
     * 获取系统消息列表
     * requestFirstPage: true表示请求首页，false表示请求下一页
     */
    fun getSystemMessageList(refresh: Boolean = true) {
        val requestPageNo = if (refresh) 1 else curPageNo + 1

        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchUserMessagesV2Query(
                    searchType = 4, // 1-Like，2-Follower，3-Comment，4-System
                    pageNo = requestPageNo,
                    pageSize = PAGE_SIZE
                ),
                showDefaultLoading = refresh
            )
            if (response?.data != null && response.data!!.fetchUserMessagesV2 != null) {
                loadSuccess()
                curPageNo = requestPageNo
                listResponse.apply {
                    pageList = response.data!!.fetchUserMessagesV2!!
                    this.refresh = refresh

                    if (this.refresh) {
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                listResponseLiveData.postValue(listResponse)
            } else {
                // 加载失败，提示用户（已toast提示）
                loadError(null)
            }
        }
    }

    companion object {
        const val PAGE_SIZE = 20
    }
}